package vip.xiaonuo.pm.modular.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.param.DeleteByIdParam;
import vip.xiaonuo.pm.modular.enterprise.entity.PmEnterpriseEntity;
import vip.xiaonuo.pm.modular.enterprise.enums.EnterpriseStatusEnum;
import vip.xiaonuo.pm.modular.enterprise.enums.EnterpriseTypeEnum;
import vip.xiaonuo.pm.modular.enterprise.mapper.PmEnterpriseMapper;
import vip.xiaonuo.pm.modular.enterprise.param.EnterpriseAddParam;
import vip.xiaonuo.pm.modular.enterprise.param.EnterpriseEditParam;
import vip.xiaonuo.pm.modular.enterprise.param.EnterprisePageParam;
import vip.xiaonuo.pm.modular.enterprise.service.PmEnterpriseService;

import java.util.List;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author xhs
 * @since 2025-06-04
 */
@Service
public class PmEnterpriseServiceImp extends ServiceImpl<PmEnterpriseMapper, PmEnterpriseEntity> implements PmEnterpriseService {

    /**
     * 根据ID查询数据
     *
     * @param id 入参
     * @return PmEnterpriseEntity
     */
    @Override
    public PmEnterpriseEntity queryEntityById(String id) {
        PmEnterpriseEntity enterpriseEntity = this.getById(id);
        if (ObjectUtil.isEmpty(enterpriseEntity)) {
            throw new CommonException("客户不存在，id值为：{}", id);
        }
        return enterpriseEntity;
    }

    /**
     * 新增客户
     *
     * @param enterpriseAddParam 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(EnterpriseAddParam enterpriseAddParam) {
        // 1.校验是否存在
        checkParam(enterpriseAddParam);
        PmEnterpriseEntity entity = BeanUtil.toBean(enterpriseAddParam, PmEnterpriseEntity.class);
        // 2.生成企业代码
        entity.setEnterpriseCode(RandomUtil.randomString(10));
        // 3.新增数据
        this.save(entity);
    }

    private void checkParam(EnterpriseAddParam enterpriseAddParam) {
        EnterpriseTypeEnum.validate(enterpriseAddParam.getEnterpriseType());
        // 企业类型为供应商是需要验证准入状态
        if (EnterpriseTypeEnum.SUPPLIER.getValue().equals(enterpriseAddParam.getEnterpriseType())) {
            EnterpriseStatusEnum.validate(enterpriseAddParam.getEnterpriseStatus());
        }
        boolean hasEnterprise = this.count(new LambdaQueryWrapper<PmEnterpriseEntity>()
                .eq(PmEnterpriseEntity::getEnterpriseType, enterpriseAddParam.getEnterpriseType())
                .eq(PmEnterpriseEntity::getEnterpriseName, enterpriseAddParam.getEnterpriseName())
        ) > 0;
        if (hasEnterprise) {
            throw new CommonException("存在重复的客户，名称为：{}", enterpriseAddParam.getEnterpriseName());
        }
    }

    /**
     * 编辑客户
     *
     * @param enterpriseEditParam 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(EnterpriseEditParam enterpriseEditParam) {
        // 1.校验是否存在
        checkParam(enterpriseEditParam);
        PmEnterpriseEntity enterpriseEntity = queryEntityById(enterpriseEditParam.getId());
        // 2.编辑数据
        BeanUtil.copyProperties(enterpriseEditParam, enterpriseEntity);
        this.updateById(enterpriseEntity);
    }

    private void checkParam(EnterpriseEditParam enterpriseEditParam) {
        EnterpriseTypeEnum.validate(enterpriseEditParam.getEnterpriseType());
        // 企业类型为供应商是需要验证准入状态
        if (EnterpriseTypeEnum.SUPPLIER.getValue().equals(enterpriseEditParam.getEnterpriseType())) {
            EnterpriseStatusEnum.validate(enterpriseEditParam.getEnterpriseStatus());
        }
        boolean hasEnterprise = this.count(new LambdaQueryWrapper<PmEnterpriseEntity>()
                .eq(PmEnterpriseEntity::getEnterpriseType, enterpriseEditParam.getEnterpriseType())
                .eq(PmEnterpriseEntity::getEnterpriseName, enterpriseEditParam.getEnterpriseName())
                .ne(PmEnterpriseEntity::getId, enterpriseEditParam.getId())
        ) > 0;
        if (hasEnterprise) {
            throw new CommonException("存在重复的客户，名称为：{}", enterpriseEditParam.getEnterpriseName());
        }
    }

    /**
     * 删除客户
     *
     * @param DeleteIdParamList 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DeleteByIdParam> DeleteIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(DeleteIdParamList, DeleteByIdParam::getId));
    }

    /**
     * 获取客户分页
     *
     * @param enterprisePageParam 入参
     * @return Page<PmEnterpriseEntity>
     */
    @Override
    public Page<PmEnterpriseEntity> page(EnterprisePageParam enterprisePageParam) {
        QueryWrapper<PmEnterpriseEntity> queryWrapper = new QueryWrapper<PmEnterpriseEntity>().checkSqlInjection();
        queryWrapper.lambda()
                .and((StringUtils.hasLength(enterprisePageParam.getSearchKey())), q ->
                        q.like(StringUtils.hasLength(enterprisePageParam.getSearchKey()), PmEnterpriseEntity::getEnterpriseName, enterprisePageParam.getSearchKey())
                                .or()
                                .like(StringUtils.hasLength(enterprisePageParam.getSearchKey()), PmEnterpriseEntity::getEnterpriseCode, enterprisePageParam.getSearchKey())
                )
                .eq(StringUtils.hasLength(enterprisePageParam.getEnterpriseAccount()), PmEnterpriseEntity::getEnterpriseAccount, enterprisePageParam.getEnterpriseAccount())
                .eq(StringUtils.hasLength(enterprisePageParam.getEnterpriseType()), PmEnterpriseEntity::getEnterpriseType, enterprisePageParam.getEnterpriseType())
                .eq(StringUtils.hasLength(enterprisePageParam.getEnterpriseStatus()), PmEnterpriseEntity::getEnterpriseStatus, enterprisePageParam.getEnterpriseStatus())
        ;
        // 处理排序
        if (ObjectUtil.isAllNotEmpty(enterprisePageParam.getSortField(), enterprisePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(enterprisePageParam.getSortOrder());
            queryWrapper.orderBy(true, enterprisePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(enterprisePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(PmEnterpriseEntity::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }
}
